#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QHostAddress>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    setWindowTitle("Client");

    ui->port->setText("8899");
    ui->ip->setText("127.0.0.1");

    ui->connect->setEnabled(true);
    ui->disconnect->setEnabled(false);

    // 创建监听的客户端对象
    m_tcp = new QTcpSocket(this);

    // 检测是否可以读取数据
    connect(m_tcp, &QTcpSocket::readyRead, this, [=]()
    {
        QByteArray data = m_tcp->readAll();
        ui->record->append("Server Say: " + data);
    });

    connect(m_tcp, &QTcpSocket::disconnected, this, [=]()
    {
//        m_tcp->close();
//        m_tcp->deleteLater();
        m_status->setPixmap(QPixmap(":/disconnect.png").scaled(20, 20));
        ui->record->append("Server and Client disconnect...");

        ui->connect->setEnabled(true);
        ui->disconnect->setEnabled(false);
    });

    connect(m_tcp, &QTcpSocket::connected, this, [=]()
    {
        m_status->setPixmap(QPixmap(":/connect.png").scaled(20, 20));
        ui->record->append("Server connect successfully...");

        ui->connect->setEnabled(false);
        ui->disconnect->setEnabled(true);
    });

    // 状态栏
    m_status = new QLabel;
    m_status->setPixmap(QPixmap(":/disconnect.png").scaled(20, 20));
    ui->statusbar->addWidget(new QLabel("Connect Status: "));
    ui->statusbar->addWidget(m_status);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_sendMsg_clicked()
{
    QString msg = ui->msg->toPlainText();
    qint64 res =  m_tcp->write(msg.toUtf8());
    // 这里检查如果真正读到了数据，记录才显示
    if(res > 0)
    {
        ui->record->append("Server Say: " + msg);
        ui->msg->setText("");
    }
    else
    {
        ui->record->append("Connect error, check Server or Client please...");
    }
}

void MainWindow::on_connect_clicked()
{
    QString ip = ui->ip->text();
    unsigned short port = ui->port->text().toUShort();
    // 个人认为 这一句 是精髓所在，只有监听了IP地址、端口号
    // 然后通过信号与槽，及时同步各线程执行情况，然后实现相应功能
    m_tcp->connectToHost(QHostAddress(ip), port);
}

void MainWindow::on_disconnect_clicked()
{
    m_tcp->close();
    ui->connect->setEnabled(true);
    ui->disconnect->setEnabled(false);
}
